﻿var wfbot = function () {

    var _config = { channel: null, endPoint: '/bot/', avEnabled: false };

    var _messageType = '';
    var _interval;
    var _received;
    var _window;
    var _nick = 'Visitor';
    var _avEnabled = false;

    // ui tags
    var $chatInput;
    var $messages;
    var $opName;
    var $visitorName;

    return {

        init: function (config) {
            if (config.endPoint) config.endPoint = '/' + config.endPoint + '/';

            $.extend(_config, config);

            send('init');

            _interval = setInterval(pull, 2000);
            _received = $('#received');

            _window = $(
				'<div id="webcallr-window" class="cf-window chat" style="position: absolute; top: 100; left: 50;">' +
				'	<div class="title">' +
				'		<div class="left"></div>' +
				'		<div id="webcallr-window-handle" class="tile">WebCallr Comm</div>' +
				'		<div class="right"></div>' +
				'	</div>' +
				'	<div class="body">' +
				'		<div class="left"></div>' +
				'		<div class="tile">' +
				'			<div class="toolbar">' +
				'				<div class="left"></div>' +
				'				<div class="tile">' +
                '                   <ul id="webcallr-chat-buttons" style="display: none;">' +
                '                       <li><a id="wfbot-show-video" href="#"><div><img src="/webcallr/images/webcam.png" /></div><div>Video Penceresi</div></a></li>' +
                '                   </ul>' +
                '               </div>' +
				'				<div class="right"></div>' +
				'			</div>' +

				'			<div class="sep"></div>' +

				'			<div class="participants">' +
				'				<ul>' +
				'					<li id="cf-op-name">WebCallr Bot</li>' +
				'					<li id="cf-visitor-name">Visitor</li>' +
				'				</ul>' +
				'			</div>' +

				'			<div class="sep"></div>' +

				'			<div class="messages">' +
				'			</div>' +

				'			<div class="sep"></div>' +

				'			<div class="input">' +
				'				<textarea name="chat-input"></textarea>' +
				'			</div>' +
				'		</div>' +
				'		<div class="right"></div>' +
				'	</div>' +
				'	<div class="bottom">' +
				'		<div class="left"></div>' +
				'		<div class="tile"></div>' +
				'		<div class="right"></div>' +
				'	</div>' +
				'</div>');

            $('body').append(_window);

            _window.draggable({ handle: '#webcallr-window-handle' });

            $chatInput = $('.cf-window textarea');
            $messages = $('.cf-window .messages');
            $opName = $('#cf-op-name');
            $visitorName = $('#cf-visitor-name');

            $chatInput.keydown(function (event) {
                if (event.keyCode == 13 && event.shiftKey == 0) {
                    message = $chatInput.val();
                    message = message.replace(/^\s+|\s+$/g, "");

                    $chatInput.val('');
                    $chatInput.focus();

                    wfbot.push({ body: message });
                    addMessage({ Sender: _nick, Body: message });

                    return false;
                }
            });

            if (_config.avEnabled) {
                $('#webcallr-chat-buttons').show();
                $('#wfbot-show-video').click(function () {
                    wfbotvideo.init();
                    return false;
                });
            }

            var cNick = $.cookie('wfbotnick');
            if (cNick != null) {
                _nick = cNick;
                $visitorName.html(_nick);
            }
        }

		, push: function (message) {
		    message.type = _messageType;
		    send('push', message, receive);
		    _messageType = '';
		}

        , enableAV: function () {
            _avEnabled = true;
        }

        , getAvailability: function (callback) {
            $.post('/communicator/getavailability', null, callback);
        }

    }

    function send(op, data, callback) {
        if (!data) data = new Object();
        data.channel = _config.channel;
        $.post(_config.endPoint + op, data, callback);
    }

    function pull() {
        send('pull', null, receive);
    }

    function receive(data) {
        if (data.length > 0) {
            for (var i = 0; i < data.length; i++) {

                if (data[i].Sender)
                    $opName.html(data[i].Sender);

                if (data[i].Type == 'textmessage') {
                    addMessage(data[i]);
                    continue;
                }

                if (data[i].Type == 'question') {

                    switch (data[i].QuestionType) {
                        case 'freetext':
                            addMessage(data[i]);
                            break;

                        case 'singleselection':
                            addSingleSelection(data[i]);
                            break;

                        case 'multiselection':
                            addMultipleSelection(data[i]);
                            break;
                    }

                    _messageType = 'response';
                    continue;
                }

                if (data[i].Type == 'command') {
                    var _command = data[i].Command;
                    var _parameter = data[i].Parameter;

                    switch (_command) {
                        case "terminate":
                            clearInterval(_interval);
                            addMessage({ Sender: 'WFBot', Body: 'Bağlantı kesildi' });
                            return;

                        default:
                            var command = eval('_command' + _command);
                            if (command) command(_parameter);
                    }
                }
            }
        }
    }

    function addMessage(message) {

        var $message;

        if (message.Sender == "WFBot")
            $message = $('<div class="message system">' + message.Body + '</div>');
        else
            $message = $('<div class="message visitor><p class="sender">' + message.Sender + '</p><p class="body">' + message.Body + '</p></div>');

        $messages.append($message);

        $messages.attr('scrollTop', $messages.attr('scrollHeight'));
    }

    function addSingleSelection(message) {
        var $question = $('<div id="' + message.Sequence + '" class="message system"><p>' + message.Body + '</p></div>');
        var options = message.Options.split('|');
        for (var i = 0; i < options.length; i++) {
            var rb = $('<div style="float: none;"><input type="radio" name="' + message.Sequence + '" value="' + options[i] + '" />' + options[i] + '</div>');
            $question.append(rb);
        }
        var btn = $('<input type="button" value="Gönder" style="width: 60px; border: 1px solid #ddcdc;" />');
        btn.click(function () {
            var checked = $('input:checked', $question);
            if (checked) {
                wfbot.push({ body: checked.val() });
            }
            $(this).attr('disabled', 'disabled');
        });
        $question.append(btn);
        $messages.append($question);

        $messages.attr('scrollTop', $messages.attr('scrollHeight'));
    }

    function addMultipleSelection(message) {
        var $question = $('<div id="' + message.Sequence + '" class="message system"><p>' + message.Body + '</p></div>');
        var options = message.Options.split('|');
        for (var i = 0; i < options.length; i++) {
            var rb = $('<div style="float: none;"><input type="checkbox" name="' + message.Sequence + '" value="' + options[i] + '" />' + options[i] + '</div>');
            $question.append(rb);
        }
        var btn = $('<input type="button" value="Gönder" style="width: 60px; border: 1px solid #ddcdc;" />');
        btn.click(function () {
            var checked = $('input:checked', $question);
            var reply = '';
            for (var i = 0; i < checked.length; i++) {
                reply += $(checked[i]).val();
                if (i < checked.length - 1) reply += '|';
            }
            if (reply != '') {
                wfbot.push({ body: reply });
            }
            $(this).attr('disabled', 'disabled');
        });
        $question.append(btn);
        $messages.append($question);

        $messages.attr('scrollTop', $messages.attr('scrollHeight'));
    }

    /* command implementations */

    function _commandsetusername(p) {
        _nick = p;
        $visitorName.html(_nick);
        $.cookie('wfbotnick', _nick);
    }

    function _commandredirecttoop(p) {
        location.href = '/communicator/index?channel=' + _config.channel + ';' + p;
    }

} ();
